<template>
  <div class="admin-dashboard-container">
    <!-- 顶部欢迎区域 -->
    <el-card class="welcome-card" shadow="hover">
      <div class="welcome-content">
        <div class="welcome-text">
          <h2>欢迎回来，管理员</h2>
          <p>{{ welcomeMessage }}</p>
        </div>
        <div class="action-buttons">
          <el-button type="primary" @click="$router.push('/order')">
            <el-icon><TrendCharts /></el-icon>订单管理
          </el-button>
          <el-button @click="$router.push('/settings')">
            <el-icon><Setting /></el-icon>系统设置
          </el-button>
        </div>
      </div>
    </el-card>
    
    <!-- 统计卡片区域 -->
    <div class="stat-cards" v-loading="statsLoading">
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-info">
            <h3>总订单数</h3>
            <div class="stat-number">{{ formatNumber(dashboardStats.totalOrders?.count || 0) }}</div>
            <div :class="['stat-trend', dashboardStats.totalOrders?.isUp ? 'up' : 'down']">
              <el-icon><ArrowUp v-if="dashboardStats.totalOrders?.isUp" /><ArrowDown v-else /></el-icon>
              <span>{{ Math.abs(dashboardStats.totalOrders?.growth || 0) }}%</span>
              <span class="trend-period">较上月</span>
            </div>
          </div>
          <div class="stat-icon document">
            <el-icon><Document /></el-icon>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-info">
            <h3>运输中订单</h3>
            <div class="stat-number">{{ formatNumber(dashboardStats.inTransitOrders?.count || 0) }}</div>
            <div :class="['stat-trend', dashboardStats.inTransitOrders?.isUp ? 'up' : 'down']">
              <el-icon><ArrowUp v-if="dashboardStats.inTransitOrders?.isUp" /><ArrowDown v-else /></el-icon>
              <span>{{ Math.abs(dashboardStats.inTransitOrders?.growth || 0) }}%</span>
              <span class="trend-period">较昨日</span>
            </div>
          </div>
          <div class="stat-icon transit">
            <el-icon><Van /></el-icon>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-info">
            <h3>今日签收</h3>
            <div class="stat-number">{{ formatNumber(dashboardStats.todayDelivered?.count || 0) }}</div>
            <div :class="['stat-trend', dashboardStats.todayDelivered?.isUp ? 'up' : 'down']">
              <el-icon><ArrowUp v-if="dashboardStats.todayDelivered?.isUp" /><ArrowDown v-else /></el-icon>
              <span>{{ Math.abs(dashboardStats.todayDelivered?.growth || 0) }}%</span>
              <span class="trend-period">较昨日</span>
            </div>
          </div>
          <div class="stat-icon completed">
            <el-icon><Check /></el-icon>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-info">
            <h3>今日收入</h3>
            <div class="stat-number">¥{{ formatNumber(dashboardStats.todayRevenue?.amount || 0, true) }}</div>
            <div :class="['stat-trend', dashboardStats.todayRevenue?.isUp ? 'up' : 'down']">
              <el-icon><ArrowUp v-if="dashboardStats.todayRevenue?.isUp" /><ArrowDown v-else /></el-icon>
              <span>{{ Math.abs(dashboardStats.todayRevenue?.growth || 0) }}%</span>
              <span class="trend-period">较昨日</span>
            </div>
          </div>
          <div class="stat-icon income">
            <el-icon><Money /></el-icon>
          </div>
        </div>
      </el-card>
    </div>
    

    
    <!-- 待处理订单 -->
    <el-card class="pending-orders-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <h3>待处理订单</h3>
          <el-button type="primary" link @click="navigateToOrders">查看全部</el-button>
        </div>
      </template>
      <el-table :data="pendingOrders" style="width: 100%" :show-header="false" v-loading="tableLoading">
        <el-table-column width="60">
          <template #default="scope">
            <el-avatar :size="36" :style="{ backgroundColor: getStatusColor(scope.row.orderStatus) }">
              {{ scope.row.orderStatus === 0 ? '新' : '待' }}
            </el-avatar>
          </template>
        </el-table-column>
        <el-table-column>
          <template #default="scope">
            <div class="order-item">
              <div class="order-number">{{ scope.row.orderNumber }}</div>
              <div class="order-info">
                {{ scope.row.senderName }} → {{ scope.row.receiverName }} | {{ getStatusText(scope.row.orderStatus) }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column width="120" align="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="processOrder(scope.row)">
              去处理
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  Document, 
  Van, 
  Check, 
  Money, 
  ArrowUp, 
  ArrowDown,
  Setting,
  TrendCharts
} from '@element-plus/icons-vue'
import { dashboardApi, adminApi, type DashboardData } from '@/api/settings'

const router = useRouter()

// 加载状态
const statsLoading = ref(true)
const tableLoading = ref(true)

// 仪表盘数据
const dashboardStats = ref<DashboardData>({
  totalOrders: { count: 0, growth: 0, isUp: true },
  inTransitOrders: { count: 0, growth: 0, isUp: true },
  todayDelivered: { count: 0, growth: 0, isUp: true },
  todayRevenue: { amount: 0, growth: 0, isUp: true },
  todayNewOrders: 0,
  systemStatus: '正常'
})

// 待处理订单数据
const pendingOrders = ref<any[]>([])

// 欢迎消息
const welcomeMessage = computed(() => {
  return `系统运行${dashboardStats.value.systemStatus}，今日共有${dashboardStats.value.todayNewOrders}个新订单`
})

// 数字格式化
const formatNumber = (num: number, isCurrency = false) => {
  if (isCurrency) {
    return num.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
  }
  return num.toLocaleString('zh-CN')
}

// 获取仪表盘数据
const fetchDashboardData = async () => {
  try {
    statsLoading.value = true
    const response = await dashboardApi.getDashboardData()
    
    if (response.code === 200 && response.data) {
      dashboardStats.value = response.data
    } else {
      console.error('获取仪表盘数据失败:', response.message)
      ElMessage.error('获取仪表盘数据失败')
    }
  } catch (error) {
    console.error('获取仪表盘数据失败:', error)
    ElMessage.error('获取仪表盘数据失败')
  } finally {
    statsLoading.value = false
  }
}

// 获取待处理订单数据
const fetchPendingOrders = async () => {
  try {
    tableLoading.value = true
    
    // 获取待处理的订单（状态为0,1,2,3的订单）
    const response = await adminApi.getAllOrders({
      pageNum: 1,
      pageSize: 10,
      keyword: '', // 不使用关键词搜索
      startDate: '', // 不限制开始日期
      endDate: '' // 不限制结束日期
    })
    
    if (response.code === 200 && response.data) {
      // 过滤出待处理的订单（状态为0,1,2,3）并只显示前8条
      const allOrders = response.data.list || []
      const pendingOrdersList = allOrders.filter((order: any) => 
        order.orderStatus >= 0 && order.orderStatus <= 3
      ).slice(0, 8)
      
      pendingOrders.value = pendingOrdersList
    } else {
      console.error('获取待处理订单失败:', response.message)
      ElMessage.error('获取待处理订单失败')
    }
  } catch (error) {
    console.error('获取待处理订单失败:', error)
    ElMessage.error('获取待处理订单失败')
  } finally {
    tableLoading.value = false
  }
}

// 获取状态文本
const getStatusText = (status: number) => {
  const statusMap: Record<number, string> = {
    0: '待揽收',
    1: '待发货',
    2: '运输中',
    3: '待签收',
    4: '已完成'
  }
  return statusMap[status] || '未知状态'
}

// 获取状态对应的颜色
const getStatusColor = (status: number) => {
  const colorMap: Record<number, string> = {
    0: '#409EFF',
    1: '#67C23A',
    2: '#E6A23C',
    3: '#F56C6C',
    4: '#909399'
  }
  return colorMap[status] || '#909399'
}

// 处理订单 - 跳转到订单管理页面
const processOrder = (order: any) => {
  // 跳转到订单管理页面，并传递订单号作为搜索参数
  router.push({
    path: '/order',
    query: {
      search: order.orderNumber
    }
  })
}

// 导航到订单页面
const navigateToOrders = () => {
  router.push('/order')
}

onMounted(() => {
  fetchDashboardData()
  fetchPendingOrders()
})
</script>

<style scoped>
.admin-dashboard-container {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
  min-height: 100%;
  width: 100%;
  padding-bottom: 20px;
  overflow: visible; /* 让内容流动，不产生独立滚动条 */
}

/* 欢迎卡片 */
.welcome-card {
  background: linear-gradient(135deg, #409EFF 0%, #1a73e8 100%);
  color: white;
  border: none;
}

.welcome-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.welcome-text h2 {
  margin: 0 0 10px 0;
  font-size: 24px;
}

.welcome-text p {
  margin: 0;
  opacity: 0.8;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

/* 统计卡片样式 */
.stat-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 20px;
  overflow: visible; /* 防止出现滚动条 */
}

.stat-card {
  border-radius: 8px;
  transition: all 0.3s;
  overflow: visible; /* 防止出现滚动条 */
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stat-info h3 {
  font-size: 14px;
  color: #909399;
  margin: 0 0 10px 0;
}

.stat-number {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 5px;
}

.stat-trend {
  display: flex;
  align-items: center;
  font-size: 12px;
  gap: 3px;
}

.stat-trend.up {
  color: #67C23A;
}

.stat-trend.down {
  color: #F56C6C;
}

.trend-period {
  color: #909399;
  margin-left: 3px;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
}

.stat-icon.document {
  background-color: #409EFF;
}

.stat-icon.transit {
  background-color: #E6A23C;
}

.stat-icon.completed {
  background-color: #67C23A;
}

.stat-icon.income {
  background-color: #F56C6C;
}

/* 卡片头部样式 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  font-size: 16px;
  font-weight: 600;
  margin: 0;
}

/* 待处理订单卡片 */
.pending-orders-card {
  min-height: 300px;
  overflow: visible; /* 防止卡片内出现滚动条 */
}

.order-item {
  display: flex;
  flex-direction: column;
}

.order-number {
  font-weight: 600;
  margin-bottom: 5px;
}

.order-info {
  font-size: 12px;
  color: #606266;
}



@media (max-width: 768px) {
  .stat-cards {
    grid-template-columns: 1fr;
  }
  
  .welcome-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
}
</style> 